package com.gitee.huxing.course.conc.task;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Description:
 * @ProjectName: JavaCourse
 * @Package: com.gitee.huxing.course.conc.task
 * @ClassName: TaskService01Impl
 * @Author: huxing
 * @DateTime: 2021-08-25 下午4:58
 */
public class TaskThreadPool21 extends AbstractTaskThreadPool{

    public static AtomicInteger atomicInteger = new AtomicInteger(0);

    private Lock lock = new ReentrantLock();

    private final Condition condition1 = lock.newCondition();

    public static void main(String[] args) throws InterruptedException{
        new TaskThreadPool21().task();
    }

    @Override
    public int threadTask() {
        lock.lock();
        try {
            Thread thread = new CustomThread(condition1, lock);
            thread.start();
            condition1.await();
            Thread.sleep(1000L);
        } catch (Exception ex){
            ex.printStackTrace();
        } finally {
            lock.unlock();
        }
        return atomicInteger.get();
    }

    static class CustomThread extends Thread{

        /** 条件锁 **/
        private Condition con1;

        /** 锁 **/
        private Lock lock;

        public CustomThread(Condition con1, Lock lock){
            this.con1 = con1;
            this.lock = lock;
        }

        @Override
        public void run() {
            lock.lock();
            try {
                atomicInteger.set(CourseTask.sum());
                con1.signal();
            } catch (Exception ex) {
                ex.printStackTrace();
            } finally {
                lock.unlock();
            }
        }
    }
}
